import * as mutationtypes from '../mutation-types';
import Vue from 'vue';
import {Map} from 'immutable';

const state = {
  goodsMap: Map(),
  currentShopGoods: []
};

const GetGoodsApi =
  (shopid) => {
    return Vue.axios.get('/WechatMall/Goods/GetGoods', {
      params: {
        shopid: shopid
      }
    });
  };

// actions
const actions = {
  RefreshCurrentShopGoods({commit}, shopid) {
    return GetGoodsApi(shopid).then((response) => {
      if (response.data.isSuccess) {
        commit(mutationtypes.SET_GOODSMAP, {value: response.data.goods, key: shopid});
      }
    });
  },
  GetCurrentShopGoods({commit, state}, shopid) {
    let list = state.goodsMap.get(shopid);
    if (list) {
      commit(mutationtypes.SET_CURRENTSHOPGOODS, list);
    } else {
      commit(mutationtypes.BEGIN_LOADING);
      GetGoodsApi(shopid).then((response) => {
        if (response.data.isSuccess) {
          commit(mutationtypes.SET_GOODSMAP, {value: response.data.goods, key: shopid});
          commit(mutationtypes.SET_CURRENTSHOPGOODS, response.data.goods);
          commit(mutationtypes.END_LOADING);
        }
      });
    }
  }
};
const getters = {};
// mutations
const mutations = {
  [mutationtypes.SET_CURRENTSHOPGOODS](state, list) {
    state.currentShopGoods = list;
  },
  [mutationtypes.SET_GOODSMAP](state, keyValuePair) {
    state.goodsMap = state.goodsMap.set(keyValuePair.key, keyValuePair.value);
  },
  [mutationtypes.ADD_CART](state, good) {
    if (!good.count) {
      Vue.set(good, 'count', 1);
    } else {
      good.count++;
    }
  },
  [mutationtypes.MINUS_CART](state, good) {
    if (good.count > 0) {
      good.count--;
    }
  },
  [mutationtypes.CLEAR_CART](state) {
    state.currentShopGoods.forEach((good) => {
      good.foods.forEach((food) => {
        if (food.count) {
          food.count = 0;
        }
      });
    });
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};
